const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = process.env.PORT || 3000;
const ENV = process.env.NODE_ENV || 'development';

// MIME 类型映射
const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.wav': 'audio/wav',
    '.mp4': 'video/mp4',
    '.woff': 'application/font-woff',
    '.woff2': 'application/font-woff2',
    '.ttf': 'application/font-ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'application/font-otf',
    '.ico': 'image/x-icon'
};

// 获取 MIME 类型
function getMimeType(filePath) {
    const ext = String(path.extname(filePath)).toLowerCase();
    return mimeTypes[ext] || 'application/octet-stream';
}

// 增强的日志记录
function log(message, type = 'info') {
    const timestamp = new Date().toISOString();
    const colors = {
        info: '\x1b[36m',    // cyan
        success: '\x1b[32m', // green
        warning: '\x1b[33m', // yellow
        error: '\x1b[31m',   // red
        reset: '\x1b[0m'     // reset
    };

    console.log(`${colors[type]}[${timestamp}] ${message}${colors.reset}`);
}

// 开发模式下的热重载提示
function injectDevScript(htmlContent) {
    if (ENV === 'development') {
        const devScript = `
<script>
// 简单的开发模式指示器
console.log('%c🚀 Development Mode Active', 'color: #00ff00; font-size: 14px; font-weight: bold;');
console.log('%c💡 For Cloudflare deployment, run: npm run deploy', 'color: #ffa500;');

// 添加开发模式横幅
window.addEventListener('load', function() {
    const banner = document.createElement('div');
    banner.innerHTML = '🛠️ Development Mode | <a href="#" onclick="location.reload()" style="color: white;">Reload</a>';
    banner.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; background: #333; color: white; text-align: center; padding: 5px; z-index: 9999; font-size: 12px;';
    document.body.insertBefore(banner, document.body.firstChild);
    document.body.style.paddingTop = '30px';
});
</script>`;

        return htmlContent.replace('</head>', devScript + '</head>');
    }
    return htmlContent;
}

const server = http.createServer((req, res) => {
    let filePath = '.' + req.url;

    // 处理根路径
    if (filePath === './') {
        filePath = './index.html';
    }

    // 处理游戏路径
    if (filePath.endsWith('/') && filePath !== './') {
        filePath = filePath + 'index.html';
    }

    const contentType = getMimeType(filePath);

    // 记录请求
    log(`${req.method} ${req.url} -> ${filePath}`, 'info');

    fs.readFile(filePath, (error, content) => {
        if (error) {
            if (error.code === 'ENOENT') {
                // 尝试读取自定义 404 页面
                fs.readFile('./404.html', (error404, content404) => {
                    if (error404) {
                        const defaultError = `
<!DOCTYPE html>
<html>
<head>
    <title>404 - Page Not Found</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin: 50px; }
        .error { color: #e74c3c; }
        .back-link { display: inline-block; margin: 20px; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; }
    </style>
</head>
<body>
    <h1 class="error">404 - Page Not Found</h1>
    <p>The requested page "${req.url}" could not be found.</p>
    <a href="/" class="back-link">← Back to Home</a>
    ${ENV === 'development' ? '<p><small>Development Mode - File: ' + filePath + '</small></p>' : ''}
</body>
</html>`;
                        res.writeHead(404, { 'Content-Type': 'text/html; charset=UTF-8' });
                        res.end(defaultError);
                        log(`404: ${filePath}`, 'warning');
                    } else {
                        res.writeHead(404, { 'Content-Type': 'text/html; charset=UTF-8' });
                        res.end(content404);
                        log(`404: ${filePath} (custom page)`, 'warning');
                    }
                });
            } else {
                res.writeHead(500, { 'Content-Type': 'text/plain' });
                res.end(`Server Error: ${error.code}`);
                log(`500: ${error.code} for ${filePath}`, 'error');
            }
        } else {
            // 处理 HTML 文件的开发模式增强
            if (contentType === 'text/html' && ENV === 'development') {
                const enhancedContent = injectDevScript(content.toString());
                res.writeHead(200, {
                    'Content-Type': contentType + '; charset=UTF-8',
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                });
                res.end(enhancedContent);
            } else {
                res.writeHead(200, {
                    'Content-Type': contentType + '; charset=UTF-8',
                    'Cache-Control': ENV === 'development' ? 'no-cache' : 'public, max-age=3600'
                });
                res.end(content);
            }
            log(`200: ${filePath}`, 'success');
        }
    });
});

server.listen(PORT, () => {
    log(`🎮 Gemini Game Hall Server`, 'success');
    log(`📍 Running at http://localhost:${PORT}/`, 'success');
    log(`🔧 Environment: ${ENV}`, 'info');
    log(`📁 Serving files from: ${path.resolve('.')}`, 'info');

    if (ENV === 'development') {
        log(``, 'info');
        log(`🛠️  Development Commands:`, 'info');
        log(`   npm run build    - Build for Cloudflare`, 'info');
        log(`   npm run preview  - Test Cloudflare build locally`, 'info');
        log(`   npm run deploy   - Deploy to Cloudflare`, 'info');
        log(``, 'info');
    }
});

// 优雅关闭
process.on('SIGINT', () => {
    log(`\n👋 Server shutting down...`, 'warning');
    server.close(() => {
        log(`✅ Server closed`, 'success');
        process.exit(0);
    });
});